﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using ComboBox = System.Windows.Forms.ComboBox;

namespace ERP_RORZE_PERMISSION.Base
{
    public class Utilities
    {
        public Utilities()
        {

        }

        public static bool IsNullOrEmpty(object o)
        {

            if (o != null && o.ToString() != "")
                return false;
            return true;
        }

        public static bool MessageConfirmationYesNo(string message)
        {
            bool flag = false;

            DialogResult result = MessageBox.Show(message, PermissionConstants.Form.MessageBox.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                flag = true;
            }

            return flag;
        }

        public static void MessageErrorOk(string message)
        {
            MessageBox.Show(message, PermissionConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void MessageOk(string message)
        {
            MessageBox.Show(message, PermissionConstants.Form.MessageBox.Message, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public class Timer
        {
            System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
            public LabelControl lb = new LabelControl();

            public Timer()
            {
                myTimer.Tick += new EventHandler(myTimer_Tick);

            }
            public void ShowHideLabel(LabelControl label, int seconds, Color color, string text)
            {
                label.ForeColor = color;
                label.Text = text;
                label.Visible = true;
                myTimer.Interval = seconds;
                myTimer.Start();
            }

            private void myTimer_Tick(object sender, EventArgs e)
            {
                lb.Visible = false;
                myTimer.Stop();
            }

        }

        public class GridUtil
        {
            public static void SelectRow(GridView gridView, int indexRow, int action = 1)
            {
                switch (action)
                {
                    case 0:
                        gridView.UnselectRow(0);
                        gridView.SelectRow(gridView.RowCount - 1);
                        gridView.FocusedRowHandle = (gridView.RowCount - 1);
                        break;
                    case 1:
                        gridView.UnselectRow(0);
                        gridView.SelectRow(indexRow);
                        gridView.FocusedRowHandle = indexRow;
                        break;
                    case 2:
                        gridView.SelectRow(0);
                        gridView.FocusedRowHandle = (0);
                        break;

                    //action
                    // 0: addnew; 1: update; 2: delete
                }
            }
        }

        public static void CreateLogFile(string fileName, string message)
        {
            FileStream fs;
            StreamReader reader;
            string tempfile = Path.GetTempFileName();
            StreamWriter writer = new StreamWriter(tempfile);

            if (File.Exists(fileName))
            {
                reader = new StreamReader(fileName);
                writer.WriteLine(String.Format("{0} :: {1}", DateTime.Now.ToString(), message));
                while (!reader.EndOfStream)
                    writer.WriteLine(reader.ReadLine());
                writer.Close();
                reader.Close();
                File.Copy(tempfile, fileName, true);
            }
            else
            {
                using (fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    writer = new StreamWriter(fs);
                    writer.WriteLine(String.Format("{0} :: {1}", DateTime.Now.ToString(), message));
                    writer.Close();
                }
            }
        }

        public static void WriteToFile(string fileName, string message)
        {
            FileStream fs;
            StreamReader reader;
            string tempfile = Path.GetTempFileName();
            StreamWriter writer = new StreamWriter(tempfile);

            if (File.Exists(fileName))
            {
                File.WriteAllText(fileName, String.Empty);
                reader = new StreamReader(fileName);
                writer.WriteLine(message);
                while (!reader.EndOfStream)
                    writer.WriteLine(reader.ReadLine());
                writer.Close();
                reader.Close();
                File.Copy(tempfile, fileName, true);
            }
            else
            {
                using (fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    writer = new StreamWriter(fs);
                    writer.WriteLine(message);
                    writer.Close();
                }
            }
        }

        public static string[] ReadFromFile(string fileName)
        {
            string[] line = new string[2];
            line[0] = "";
            line[1] = "";

            if (File.Exists(fileName))
            {

                System.IO.StreamReader file = new System.IO.StreamReader(fileName);
                for (int i = 0; i < 2; i++)
                {
                    line[i] = file.ReadLine();
                }

                //MessageBox.Show(line[0] + " || " + line[1]);
                file.Close();
            }

            return line;
        }
        public static string Encrypt(string passwordHash, string saltKey, string vIKey, string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(passwordHash, Encoding.ASCII.GetBytes(saltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(vIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return Convert.ToBase64String(cipherTextBytes);
        }

        public static string Decrypt(string passwordHash, string saltKey, string vIKey, string encryptedText)
        {
            string result = "";
            if (IsBase64String(encryptedText))
            {
                byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
                byte[] keyBytes = new Rfc2898DeriveBytes(passwordHash, Encoding.ASCII.GetBytes(saltKey)).GetBytes(256 / 8);
                var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

                var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(vIKey));
                var memoryStream = new MemoryStream(cipherTextBytes);
                var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];

                int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                memoryStream.Close();
                cryptoStream.Close();
                result = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());

            }
            return result;
        }

        public static string EncryptPassword(string strEnCrypt, string key)
        {
            try
            {
                byte[] keyArr;
                byte[] EnCryptArr = Encoding.UTF8.GetBytes(strEnCrypt);
                MD5CryptoServiceProvider MD5Hash = new MD5CryptoServiceProvider();
                keyArr = MD5Hash.ComputeHash(Encoding.UTF8.GetBytes(key));
                TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider();
                tripDes.Key = keyArr;
                tripDes.Mode = CipherMode.ECB;
                tripDes.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = tripDes.CreateEncryptor();
                byte[] arrResult = transform.TransformFinalBlock(EnCryptArr, 0, EnCryptArr.Length);
                return Convert.ToBase64String(arrResult, 0, arrResult.Length);
            }
            catch (Exception ex) { }
            return "";
        }

        public static bool IsBase64String(string s)
        {
            s = s.Trim();
            return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);

        }

        public static void ExportToExcel(GridView gridView, int type, bool openNow)
        {
            if (gridView == null) return;

            //First: Change gridView's property PrintSelectedRowOnly to True
            gridView.OptionsPrint.PrintSelectedRowsOnly = true;
            gridView.OptionsSelection.MultiSelect = true;
            switch (type)
            {
                //0: Export selected rows
                case 0:
                    if (gridView.RowCount > 0)
                    {
                        try
                        {
                            bool success = false;
                            XlsxExportOptions option = new XlsxExportOptions();
                            option.ShowGridLines = true;
                            option.SheetName = gridView.ViewCaption;
                            //option.TextExportMode = te

                            FileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Filter = PermissionConstants.Configuration.FilterFile.Excel;
                            fileDialog.FileName = gridView.ViewCaption;
                            if (fileDialog.ShowDialog() == DialogResult.OK)
                            {
                                //gridView.BeginUpdate();
                                //gridView.BestFitColumns();
                                //gridView.Columns[1].Visible = false;
                                //gridView.Columns[2].Visible = false;
                                //gridView.Columns[3].Visible = false;
                                gridView.ExportToXlsx(fileDialog.FileName, option);
                                //gridView.Columns[1].Visible = true;
                                //gridView.Columns[2].Visible = true;
                                //gridView.Columns[3].Visible = true;
                                //gridView.EndUpdate();
                                success = true;

                            }

                            if (success && openNow && MessageBox.Show(PermissionConstants.Message.QuestionOpenFileExport, PermissionConstants.Form.MessageBox.Message, MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                Process process = new Process();
                                process.StartInfo.FileName = fileDialog.FileName;
                                process.StartInfo.Verb = "Open";
                                process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                                process.Start();

                            }

                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message, PermissionConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    else
                    {
                        MessageBox.Show(PermissionConstants.Message.NoDataToExport, PermissionConstants.Form.MessageBox.Message,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;

                //1: Export all
                case 1:
                    if (gridView.RowCount > 0)
                    {
                        try
                        {
                            bool success = false;
                            XlsxExportOptions option = new XlsxExportOptions();
                            option.ShowGridLines = true;
                            option.SheetName = gridView.ViewCaption;

                            FileDialog fileDialog = new SaveFileDialog();
                            fileDialog.Filter = PermissionConstants.Configuration.FilterFile.Excel;
                            fileDialog.FileName = gridView.ViewCaption;
                            if (fileDialog.ShowDialog() == DialogResult.OK)
                            {
                                gridView.BestFitColumns();
                                gridView.SelectAll();
                                gridView.ExportToXlsx(fileDialog.FileName, option);
                                success = true;
                            }

                            if (success && openNow && MessageBox.Show(PermissionConstants.Message.QuestionOpenFileExport, PermissionConstants.Form.MessageBox.Message, MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                Process process = new Process();
                                process.StartInfo.FileName = fileDialog.FileName;
                                process.StartInfo.Verb = "Open";
                                process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                                process.Start();

                            }
                        }
                        catch (Exception ex)
                        {

                            MessageBox.Show(ex.Message, PermissionConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }
                    else
                    {
                        MessageBox.Show(PermissionConstants.Message.NoDataToExport, PermissionConstants.Form.MessageBox.Message,
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;

                default:
                    break;
            }

        }

        public static void ExportToExcelExtraSheet(List<GridControl> listGridView, bool openNow, string name)
        {
            if (listGridView.Count < 1) return;

            var printingSystem = new PrintingSystemBase();
            var compositeLink = new CompositeLinkBase();
            compositeLink.PrintingSystemBase = printingSystem;


            var options = new XlsxExportOptions();
            options.ExportMode = XlsxExportMode.SingleFilePageByPage;
            options.ShowGridLines = true;

            if (listGridView.Count > 0)
            {

                try
                {
                    bool success = false;
                    FileDialog fileDialog = new SaveFileDialog();
                    fileDialog.Filter = PermissionConstants.Configuration.FilterFile.Excel;
                    fileDialog.FileName = name;
                    if (fileDialog.ShowDialog() == DialogResult.OK)
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        foreach (GridControl grid in listGridView)
                        {
                            ((GridView)grid.DefaultView).OptionsPrint.PrintSelectedRowsOnly = false;
                            var printingSystem1 = new PrintingSystemBase();
                            var link = new PrintableComponentLinkBase();
                            link.Component = grid;
                            link.PrintingSystemBase = printingSystem1;
                            link.PrintingSystemBase.ExportOptions.Xlsx.SheetName = grid.DefaultView.ViewCaption;
                            link.PrintingSystemBase.ExportOptions.Xls.SheetName = grid.DefaultView.ViewCaption;

                            compositeLink.Links.Add(link);
                        }

                        compositeLink.CreatePageForEachLink();
                        compositeLink.ExportToXlsx(fileDialog.FileName, options);
                        success = true;
                        Cursor.Current = Cursors.Default;

                    }

                    if (success && openNow && MessageBox.Show(PermissionConstants.Message.QuestionOpenFileExport, PermissionConstants.Form.MessageBox.Message, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        Process process = new Process();
                        process.StartInfo.FileName = fileDialog.FileName;
                        process.StartInfo.Verb = "Open";
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                        process.Start();

                    }
                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.Message, PermissionConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else
            {
                MessageBox.Show(PermissionConstants.Message.NoDataToExport, PermissionConstants.Form.MessageBox.Message,
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public class ComboboxItem
        {
            public string Text { get; set; }
            public object Value { get; set; }

            public override string ToString()
            {
                return Text;
            }
        }

        public class ItemGridColumn
        {
            protected GridColumn column = new GridColumn();
            protected int index;

            public GridColumn Column
            {
                get { return column; }

                set { column = value; }
            }

            public int VisibleIndex
            {
                get { return index; }

                set { index = value; }
            }


        }

        public class ListItem
        {
            public string ID { get; set; }
            public string Value { get; set; }
            public string Note { get; set; }

            public override string ToString()
            {
                return Value;
            }

            public ListItem(string iD, string value, string note = null)
            {
                this.ID = iD;
                this.Value = value;
                this.Note = note;
            }
        }

        public static void AdjustWidthComboBox(object sender, EventArgs e)
        {
            ComboBox senderComboBox = (ComboBox)sender;
            int width = senderComboBox.DropDownWidth;
            Graphics g = senderComboBox.CreateGraphics();
            Font font = senderComboBox.Font;
            int vertScrollBarWidth =
                (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
                ? SystemInformation.VerticalScrollBarWidth : 0;

            int newWidth;
            foreach (object item in ((ComboBox)sender).Items)
            {
                newWidth = (int)g.MeasureString(item.ToString(), font).Width
                    + vertScrollBarWidth;
                if (width < newWidth)
                {
                    width = newWidth;
                }
            }
            senderComboBox.DropDownWidth = width;
        }
    }
}
